#!/usr/bin/env python

import os
import shlex
import sys

def resolve(path):
    if os.path.islink(path):
        path = os.path.join(os.path.dirname(path), os.readlink(path))
        return resolve(path)
    return path

SUPPORTED_ENGINES = {
    'phantomjs' : {
        'native_args': [
            'cookies-file',
            'config',
            'debug',
            'disk-cache',
            'disk-cache-path',
            'ignore-ssl-errors',
            'load-images',
            'load-plugins',
            'local-storage-path',
            'local-storage-quota',
            'local-to-remote-url-access',
            'max-disk-cache-size',
            'output-encoding',
            'proxy',
            'proxy-auth',
            'proxy-type',
            'remote-debugger-port',
            'remote-debugger-autorun',
            'script-encoding',
            'ssl-protocol',
            'ssl-certificates-path',
            'web-security',
            'webdriver',
            'webdriver-logfile',
            'webdriver-loglevel'
            'webdriver-selenium-grid-hub',
            'wd',
            'w',
        ],
        'env_varname': 'PHANTOMJS_EXECUTABLE',
        'default_exec' : 'phantomjs'
    },
    'slimerjs': {
        'native_args': [
            '-P',
            '-jsconsole',
            '-CreateProfile',
            '-profile',
            #phantomjs options
            'cookies-file',
            'config',
            'debug',
            'disk-cache',
            'ignore-ssl-errors',
            'load-images',
            'load-plugins',
            'local-storage-path',
            'local-storage-quota',
            'local-to-remote-url-access',
            'max-disk-cache-size',
            'output-encoding',
            'proxy',
            'proxy-auth',
            'proxy-type',
            'remote-debugger-port',
            'remote-debugger-autorun',
            'script-encoding',
            'ssl-protocol',
            'ssl-certificates-path',
            'web-security',
            'webdriver',
            'webdriver-logfile',
            'webdriver-loglevel'
            'webdriver-selenium-grid-hub',
            'wd',
            'w',
        ],
        'env_varname': 'SLIMERJS_EXECUTABLE',
        'default_exec' : 'slimerjs'
    },
}

ENGINE = os.environ.get('CASPERJS_ENGINE', 'phantomjs')
ENGINE_ARGS = shlex.split(os.environ.get('ENGINE_FLAGS', ''))
ENGINE_NATIVE_ARGS = []
ENGINE_EXECUTABLE = ''

CASPER_ARGS = []
CASPER_PATH = os.path.abspath(os.path.join(os.path.dirname(resolve(__file__)),
                                           '..'))
SYS_ARGS = sys.argv[1:]

# retrieve the engine name
for arg in SYS_ARGS:
    if arg.startswith('--engine='):
        ENGINE = arg[9:].lower()
        break

if not ENGINE in SUPPORTED_ENGINES:
    print('Bad engine name. Only phantomjs and slimerjs are supported')
    sys.exit(1)

ENGINE_NATIVE_ARGS = SUPPORTED_ENGINES[ENGINE]['native_args']
ENGINE_EXECUTABLE = os.environ.get(SUPPORTED_ENGINES[ENGINE]['env_varname'],
                                   os.environ.get('ENGINE_EXECUTABLE',
                                       SUPPORTED_ENGINES[ENGINE]['default_exec']))

def extract_arg_name(arg):
    "parse out any option name"
    try:
        return arg.split('=', 1)[0].replace('--', '', 1)
    except IndexError:
        return arg

for arg in SYS_ARGS:
    arg_name = extract_arg_name(arg)
    found = False
    for native in ENGINE_NATIVE_ARGS:
        if arg_name == native:
            ENGINE_ARGS.append(arg)
            found = True
    if not found and arg_name != 'engine':
        CASPER_ARGS.append(arg)

CASPER_COMMAND = [ENGINE_EXECUTABLE]
CASPER_COMMAND.extend(ENGINE_ARGS)
CASPER_COMMAND.extend([
    os.path.join(CASPER_PATH, 'bin', 'bootstrap.js'),
    '--casper-path=%s' % CASPER_PATH,
    '--cli'
])
CASPER_COMMAND.extend(CASPER_ARGS)

try:
    # print(CASPER_COMMAND)
    os.execvp(CASPER_COMMAND[0], CASPER_COMMAND)
except OSError as err:
    print('Fatal: %s; did you install %s?' % (err, ENGINE))
    sys.exit(1)
